var vnkit_nam_hoc = edu_default_nam_hoc;
//if (vnkit_nam_hoc_default > 0) vnkit_nam_hoc = vnkit_nam_hoc_default;
vnkit_site.itype = parseInt(vnkit_site.itype);
var setRoleTbar = function(tbar, v)
{
    if (tbar.items)
    {
        for (var i = 0; i < tbar.items.length; ++i)
        {
            var me = tbar.items.get(i);
            if (me.checkRole && me.checkRole === true)
                if (!me.role2 || me.role2 === false)
                    me.setDisabled(v);
            setRoleTbar(me, v);
        }
    }
    
    if (tbar.menu && tbar.menu.items)
    {
        for (var i = 0; i < tbar.menu.items.length; ++i)
        {
            var me = tbar.menu.items.get(i);
            if (me.checkRole && me.checkRole === true)
                me.setDisabled(v);
            setRoleTbar(me, v);
        }
    }
}
var getStrNamHoc = function(s)
{
    if (s === 1) return '<span>' + vnkit_nam_hoc + '-' + (parseInt(vnkit_nam_hoc) + 1) + '</span>';
    else return '[' + vnkit_nam_hoc + '-' + (parseInt(vnkit_nam_hoc) + 1) + '] ';
};

var getStrNamHoc2 = function(i, s)
{
    if (s === 1) return '<span>' + i + '-' + (parseInt(i) + 1) + '</span>';
    else return '[' + i + '-' + (parseInt(i) + 1) + '] ';
};

var openNotify = function(args)
{
    var i = 0;
    var win = false;
    for (i=0; i<=100; ++i){
        win = Ext.getCmp("frm_open_notify_" + i);
        if (!win) break;
    }
    var winId = "frm_open_notify_" + i;
    win = new Ext.window.Window({
        id : winId,
        iconCls : args.iconCls ? args.iconCls : "info16",
        plain : false,
        width : args.width ? args.width : 200,
        height : args.height ? args.height : 100,
        closable : true,
        frameHeader : false,
        title : args.title ? args.title : "System",
        bodyPadding : 10,
        html : args.html ? args.html : ""
    });

    win.animateTarget = args.from ? args.from : 'btnUnikey';
    win.x = $('body').width() - win.width;
    win.y = $('body').height() - win.height - win.height * i - i*2 - $('.ux-taskbar').height() - 3;

    win.show();
    
    args.time = args.time ? args.time : 7000;
    setTimeout("Ext.getCmp('" + winId + "').close();", args.time);
};

var open_csdl = function(nam_hoc, idMenu)
{
    $.ajax({
        url : "?call=param.set",
        type : "POST",
        dataType : "html",
        data : {"name" : "user.nam_hoc", "value" : nam_hoc},
        success : function(){
            vnkit_nam_hoc = nam_hoc;
            $('#lblNamHoc .x-btn-inner span').html(getStrNamHoc(1));
            openNotify({html : "Hệ thống đã mở Cơ sở dữ liệu năm học " + nam_hoc + " - " + (nam_hoc + 1) + " thành công."});
            updateTongKet(vnkit_nam_hoc, false);
        },
        error : function (a,b,c){}
    });    
};

var onExtSubmitError = function(form, action)
{
    switch (action.failureType) 
    {
        case Ext.form.action.Action.CLIENT_INVALID:
            Ext.Msg.alert('Failure', 'Form fields may not be submitted with invalid values');
            break;
        case Ext.form.action.Action.CONNECT_FAILURE:
            Ext.Msg.alert('Failure', 'Ajax communication failed');
            break;
        case Ext.form.action.Action.SERVER_INVALID:
            Ext.Msg.alert('Thông báo', action.result.msg);
    }
    
    Ext.util.Mask.hide();
};

var check_status = function()
{
    $.ajax({
        url : "?call=auth.check",
        dataType : "script",
        data : {"user_id" : vnkit_user_id},
        error : function (a,b,c){}
    });
    
    setTimeout("check_status();", 30000);
};

//if (!vnkit_is_local)
    setTimeout("check_status();", 5000);

var setUnikey = function()
{
    $("#btnUnikey").click(function(){
        var me = $(".btnUnikeyCls");
        if (Mudim.method != 4)
        {
            me.removeClass("icon-en");
            me.addClass("icon-vi");
            Mudim.SetMethod(4);
        }
        else
            {
                me.removeClass("icon-vi");
                me.addClass("icon-en");
                Mudim.SetMethod(0);
            }
    });
};

var autoTaskbar = function()
{
    if ($('#apn-null-toolbar').length)
    {
        var top = $('body').height();
        top = top - $('#apn-null-toolbar').height() - $('.ux-taskbar').height();
        $('.ux-taskbar').css("top", top);
    }
};
var autoRun = function()
{
    setUnikey();
    
    autoTaskbar();
    
    $(desktop_shortcut).each(function(){
        if(this.autorun === 1)
        {
            var args = this.args ? eval('(' + this.args + ')') : {};
            if (!args.iconCls) args.iconCls = this.iconClsMi;
            if (args.set_nam_hoc)
                vnkit_nam_hoc = args.set_nam_hoc;
            if (args.nam_hoc)
            {
                args.nam_hoc = vnkit_nam_hoc;
                args.title = args.title ? getStrNamHoc() + args.title : getStrNamHoc() + this.text;
            }
            var win = Ext.create(this.open_class);
            win = win.createWindow(args);
        }
    });
    
    
    var top = 6;
    var height = 600;
    var width = 160;
    var divqc = $('<div class="quangcao_nen"></div>');
    $('body').append(divqc);

    var aqc = [
        //"linkvietnamnet_336x140_12.swf", 
        //"trungdich_336x140_3.swf", 
        //"vnnet_336-x-140.swf",
        //"160x600-vnn-15-2.swf"
    ];
    for (var i = 0; i < aqc.length; ++i)
    {
        var qc = '<object class="quangcao" id="swf_ADS_64_15s_0" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" border="0" height="' + height + '" width="' + width + '">';
            qc += '<param name="movie" value="resources/images/' + aqc[i] + '">';
            qc += '<param name="AllowScriptAccess" value="always">';
            qc += '<param name="quality" value="High">';
            qc += '<param name="wmode" value="transparent">';
            qc += '<embed src="resources/images/' + aqc[i] + '" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" wmode="transparent" allowscriptaccess="always" height="' + height + '" width="' + width + '">';
            qc += '</object>';

        qc = $(qc);
        qc.css("top", top + top * i + height * i);
        divqc.append(qc);
    }

//        divqc.mouseover(function(){
//            var me = $(this);
//            me.css("opacity", "1");
//            me.css("filter", "alpha(opacity=100)");
//        });
//        
//        divqc.mouseout(function(){
//            var me = $(this);
//            me.css("opacity", "0.3");
//            me.css("filter", "alpha(opacity=30)");
//        });    

//        var win = new Ext.window.Window({
//            iconCls : "icon-new",
//            plain : true,
//            width : 200,
//            height : 100,
//            closable : true,
//            frameHeader : false,
//            title : "Thông báo"
//        });
//        
//        win.animateTarget = 'btTaskbarFeedback';
//        win.x = $('body').width() - win.width;
//        win.y = $('body').height() - win.height - $('.ux-taskbar').height() - 2;
//        
//        win.show();

    updateTongKet(vnkit_nam_hoc, false);
    openNotify({html : "Chào bạn <b>" + vnkit_user.full_name + "</b>,<br>Hệ thống đã khởi động xong."});
};


Ext.define('vnKit.App', {
    extend: 'Ext.ux.desktop.App',

    requires: [
        'Ext.window.MessageBox',
        'Ext.ux.desktop.ShortcutModel'
    ],

    init: function() {
        
        this.callParent();

        autoTaskbar();
        
        setTimeout("autoRun();", 1000);                
        
        Ext.util.Mask.hide();
    },

    getModules : function(){
        return new vnKit.Core.StartMenu();
    },

    getDesktopConfig: function () {
        var me = this, ret = me.callParent();

        return Ext.apply(ret, {
            //cls: 'ux-desktop-black',
            contextMenuItems: [
                {text: 'Ẩn tất cả cửa sổ', handler: me.onMinimizeAll, scope: me, minWindows: 1},
                {text: 'Hiện tất cả cửa sổ', handler: me.onRestoreAll, scope: me, minWindows: 1},
                {text: 'Tắt tất cả cửa sổ', handler: me.onCloseAll, scope: me, minWindows: 1},
//                {text: 'Tile windows', handler: me.onTileWindows, scope: me, minWindows: 1},
                {text: 'Tự động sắp xếp', handler: me.onCascadeWindows, scope: me, minWindows: 1},
                '-',
                {text: 'Cấu hình hệ thống', handler: me.onSettings, scope: me, iconCls:'settings'}
            ],

            shortcuts: Ext.create('Ext.data.Store', {
                model: 'Ext.ux.desktop.ShortcutModel',
                data: desktop_shortcut
            }),

            wallpaper: 'file/download/' + vnkit_wallpaper_id + '.html',
            wallpaperStretch: vnkit_wallpaper_stretch
        });
    },

    // config for the start menu
    getStartConfig : function() {
        var me = this, ret = me.callParent();

        return Ext.apply(ret, {
            id : 'startmenu_container',
            title: "",//<span id='lblCurrentUser'>" + (vnkit_user_name ? vnkit_user_name + ' - ' : "Guest") + vnkit_user_full_name + "</span>",
            iconCls: 'user',
            height: 418,
            toolConfig: {
                items: [
//                    {
//                        html:'<div style="height:115px; width:115px; background-image: none; overflow: hidden;"><div class="imgAvatar_' + vnkit_user_id + '" style="height:115px; width:115px; background-image: url(file/thumb/115/115/' + vnkit_avatar_id  + '.jpg?r=' + Math.random() + '); overflow: hidden;"></div></div>',
//                        handler: function(){
//                            var frm = new vnKit.User.ChangeAvatar();
//                            frm.createWindow({"name" : "Avatar"});
//                        },
//                        scope: me
//                    },
                    {
                        text:'Đổi ảnh đại diện',
                        iconCls:'avatar16',
                        handler: function(){
                            if (vnkit_user_id === 0)
                            {
                                window.location.href = vnkit_url_login;
                                return;
                            }
                            var frm = new vnKit.User.ChangeAvatar();
                            frm.createWindow({"name" : "Avatar"});
                        },
                        scope: me
                    },
                    {
                        text:'Hồ sơ cá nhân',
                        iconCls:'info16',
                        handler: function(){
                            if (vnkit_user_id === 0)
                            {
                                window.location.href = vnkit_url_login;
                                return;
                            }
                            var frm = new vnKit.User.Info();
                            frm.createWindow({"name" : "Hồ sơ cá nhân", "title":"Hồ sơ cá nhân"});
                        },
                        scope: me
                    },
                    {
                        text:'Thay đổi mật khẩu',
                        iconCls:'key16',
                        handler: me.onChangePassword,
                        scope: me
                    },                    
                    {
                        text:'Lịch sử đăng nhập',
                        iconCls:'access16',
                        handler: function(){
                            if (vnkit_user_id === 0)
                            {
                                window.location.href = vnkit_url_login;
                                return;
                            }
                            var frm = new vnKit.User.LoginHistory();
                            frm.createWindow({"name" : "Lịch sử đăng nhập"});
                        },
                        scope: me
                    },
                    '-',
                    {
                        text:'Cấu hình hệ thống',
                        iconCls:'config16',
                        handler: me.onSettings,
                        scope: me
                    },
                    {
                        id : "btnUnikey1",
                        text:'Bật tắt Tiếng Việt',
                        iconCls:'btnUnikeyCls ' + (($.readCookie("unikey") == 4)? "icon-vi" : "icon-en") ,
                        handler: function(){
                            $("#btnUnikey").click();
                            return false;
                        },
                        scope: me
                    },
                    '-',
                    {
                        text: (vnkit_user_id !== "") ? 'Logout, Đăng xuất' : 'Login - Đăng nhập',
                        iconCls:'logout16',
                        handler: me.onLogout,
                        scope: me
                    }
                ]
            }
        });
    },

    getTaskbarConfig: function () {
        var ret = this.callParent();
        var tray = [];
        if (vnkit_site.itype === 1 || vnkit_site.itype === 3 || vnkit_site.itype === 4 || vnkit_site.itype === 5 || vnkit_site.itype === 8 || vnkit_site.itype === 10)
            tray = [
            {
                id : "btTaskbarFeedback",
                iconCls: 'feed16',
                width : 75,
                text : "Trao đổi",
                //"pressed" : true,
                handler : function(){
                    var win = new vnKit.Feed.Home();
                    win.createWindow({wallid : '52311cd27eca1096119534e22573a0df'}); 
                }
            },
            '-',
            {
                iconCls: 'year',
                //hidden : vnkit_site.itype === 1 ? false : true,
                id : "lblNamHoc",
                text : getStrNamHoc(1),
                handler : function(){

                }
                ,
                menu:[
                    {
                        iconCls: 'year',
                        text : '2013-2014',
                        handler : function(){
                            open_csdl(2013);
                        }
                    },
                    {
                        iconCls: 'year',
                        text : '2012-2013',
                        handler : function(){
                            open_csdl(2012);
                        }
                    }
                ]
            },
            '-',
            {id : "btnUnikey", name: 'Bộ gõ', iconCls: 'btnUnikeyCls icon-en'}, 
            {xtype: 'trayclock', flex: 1}                                
        ];
        else tray = [
            {
                id : "btTaskbarFeedback",
                iconCls: 'feed16',
                width : 75,
                text : "Trao đổi",
                //"pressed" : true,
                handler : function(){
                    var win = new vnKit.Feed.Home();
                    win.createWindow({wallid : '52311cd27eca1096119534e22573a0df'}); 
                }
            },
            '-',
            {id : "btnUnikey", name: 'Bộ gõ', iconCls: 'btnUnikeyCls icon-en'}, 
            {xtype: 'trayclock', flex: 1}                                
        ];
        
        return Ext.apply(ret, {
            quickStart: desktop_quickstart,
            trayItems: tray
        });
    },

    onLogout: function () {
        if (vnkit_user_id !== "")
        {
            Ext.Msg.confirm('Đăng xuất', 'Đăng xuất khỏi hệ thống?', 
                function(btn){
                    if (btn === "yes")
                        window.location.href = vnkit_url_logout;
                }
            );
        }
        else
        {
            window.location.href = vnkit_url_login;
        }
    },

    onSettings: function () {
        var dlg = new vnKit.Desktop.Preferences();
        dlg.createWindow({
            desktop: this.desktop
        });
    },
    
    onChangePassword: function () {
        if (vnkit_user_id === "")
        {
            window.location.href = vnkit_url_login;
            return;
        }
        var dlg = new vnKit.User.ChangePassword();
        dlg.createWindow({"name" : "Đổi mật khẩu"});
    },
    
    onCloseAll : function(){
        var desktop = this.desktop;
        
        desktop.getWindows().each(function(win) {
           win.close(); 
        });
    },
    
    onMinimizeAll : function(){
        var desktop = this.desktop;
        
        desktop.getWindows().each(function(win) {
           win.minimize(); 
        });
    },
    
    onRestoreAll : function(){
        var desktop = this.desktop;
        desktop.getWindows().each(function(win) {
           win.show();
           win.restore(); 
           win.toFront();
        });
    },
    
    onTileWindows : function()
    {
        var desktop = this.desktop;
        desktop.tileWindows();
    },
    
    onCascadeWindows : function()
    {
        var desktop = this.desktop;
        desktop.cascadeWindows();
    }
});

